package com.imooc.order.controller;

import com.imooc.order.client.ProductClient;
import com.imooc.order.dataobject.ProductInfo;
import com.imooc.order.dto.CartDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

@RestController
@Slf4j
public class ClientController {

    @Autowired
    private ProductClient productClient;

//    @Autowired
//    private LoadBalancerClient loadBalancerClient;
//
////    @Autowired
////    private RestTemplate restTemplate;
//
//    @GetMapping("/getProductMsg")
//    public String getProductMsg() {
//
//        //第一种( 直接使用 RestTemplate ， url写死)
////        RestTemplate restTemplate = new RestTemplate();
////        String response = restTemplate.getForObject("http://localhost:8080/msg", String.class);
//
//
//        //第二种(利用 注解 LoadBalancerClient 通过 应用名获取 url,在使用 RestTemplate)
//        RestTemplate restTemplate = new RestTemplate();
//        ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
//        String url = String.format("http://%s:%s", serviceInstance.getHost(), serviceInstance.getPort()) + "/msg";
//        String response = restTemplate.getForObject(url, String.class);
//
//
//        //第三种(利用注解LoadBalanced，可在 restTemplate里使用应用名)
//
//        return response;
//
//    }

    @GetMapping("/getProductMsg")
    public String getProductMsg() {

        //通过feign
        String response = productClient.productMsg();
        return response;
    }

    @GetMapping("/getProductList")
    public String getProductList() {

        //通过feign
        List<ProductInfo> productInfos = productClient.listForOrder(Arrays.asList("1"));
        log.info("response={}", productInfos);
        return "OK";
    }

    @GetMapping("/decreaseStock")
    public String decreaseStock() {
        productClient.decreaseStock(Arrays.asList(new CartDTO("1", 2)));
        return "OK";
    }


}
